package com.bafa.services.results;

import java.util.Calendar;
import java.util.HashMap;

import com.bafa.dbcache.LeagueCache;
import com.bafa.debug.Debug;
import com.bafa.exceptions.ErrorException;
import com.bafa.jdbc.DBAccess;
import com.bafa.jdbc.QueryObject;
import com.bafa.jdbc.UpdateObject;
import com.bafa.objects.Match;
import com.bafa.objects.Message;
import com.bafa.objects.team.Team;
import com.bafa.services.LeagueTableServices;
import com.bafa.services.MiddleUtils;
import com.bafa.services.RetrieveServices;
import com.bafa.services.scorers.FunctionalScorerServices;
import com.bafa.services.scorers.ScorersServices;

public class ResultServices {

	/**
	 * to be used by the admin
	 */
	public static Message addResult(int matchId, int goalsA, int goalsB,
			String[] scorersA, String[] scorerGoalsA, String[] scorersB,
			String[] scorerGoalsB, int teamA, int teamB, boolean walkover,
			int divisionId) {
		DBAccess db = new DBAccess();
		Message message = new Message();
		Match match = RetrieveServices.getMatch(matchId);
		try {
			FunctionalResultsServices.addScores(match, goalsA, goalsB, true);
			FunctionalResultsServices.addScores(match, goalsA, goalsB, false);
			if (!walkover) {
				FunctionalScorerServices.addScorers(db, match, scorersA,
						scorerGoalsA, RetrieveServices.getTeam(teamA + ""),
						true);
				FunctionalScorerServices.addScorers(db, match, scorersB,
						scorerGoalsB, RetrieveServices.getTeam(teamB + ""),
						false);
			}

			FunctionalResultsServices.confirmResult(matchId);
			LeagueCache.getUnplayedMatches().remove(match.getID());
			db.updateMatch(match);
			message
					.addMessage("Result has been updated successfully and confirmed. Scorers can been edited in future");

		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			db.disconnect();

			RetrieveServices.getTeam(teamA + "").getStats().updateScores(match,
					match.getSeasonId());
			RetrieveServices.getTeam(teamB + "").getStats().updateScores(match,
					match.getSeasonId());
			RetrieveServices.getDivision("" + match.getSeasonId(),
					"" + match.getDivision()).refreshTeams();

			try {
				db.updateTeam(RetrieveServices.getTeam(teamA + ""));
				db.updateTeam(RetrieveServices.getTeam(teamB + ""));
			} catch (Exception e) {

			}

			if (RetrieveServices.getCurrentSeason().isCompleted()) {
				message.addMessage("This season is over......");
			}
		}
		return message;
	}

	public static Message addResult(int matchId, int goalsA, int goalsB,
			String[] scorers, String[] goals, int teamId, String user,
			int divisionId) throws ErrorException {
		Message message = new Message();
		DBAccess db = new DBAccess();
		Team team = RetrieveServices.getTeam("" + teamId);
		Match match = RetrieveServices.getMatch(matchId);
		boolean home = MiddleUtils.isHome(match, teamId);

		boolean weAdded = (home) ? match.isHomeAdded() : match.isAwayAdded();
		boolean oppoAdded = (home) ? match.isAwayAdded() : match.isHomeAdded();
		Debug.debug(new ResultServices().getClass(),"addResult","Have we added the result already: "+weAdded);
		Debug.debug(new ResultServices().getClass(),"addResult","Have they added the result already: "+oppoAdded);
		if (weAdded) {
			message
					.addMessage("You've already added the result for this match.");

		} else if (!oppoAdded) {
			try {
				FunctionalResultsServices
						.addScores(match, goalsA, goalsB, home);
				FunctionalScorerServices.addScorers(db, match, scorers, goals,
						team, home);
				LeagueCache.getUnplayedMatches().remove(match.getID());
				db.updateMatch(match);
				RetrieveServices.getTeam(match.getTeamA() + "").getStats()
				.updateScores(match, match.getSeasonId());
		RetrieveServices.getTeam(match.getTeamB() + "").getStats()
				.updateScores(match, match.getSeasonId());
				message
						.addMessage("You've entered your result successfully. Though you will see the league table updated instantly, this match is unconfirmed until your opponents enter the result");
			} catch (Exception e) {
				message.addMessage("Result has not been added.");
				e.printStackTrace();
			}
		} else if (oppoAdded) {

			if (match.getGoalsA() == goalsA && match.getGoalsB() == goalsB) {
				try {
					FunctionalScorerServices.addScorers(db, match, scorers,
							goals, team, home);
					FunctionalResultsServices.confirmResult(matchId);
					message
							.addMessage("You're scorers have been added and the result has been confirmed.");
				} catch (Exception e) {
					message.addError("Result has not been added.");
					e.printStackTrace();
				}
			} else {
				message
						.addError("There has been a dispute in the result. Please contact "+db.retrieveReference("adminemailaddress"));
				FunctionalResultsServices.resultDisputed(matchId);
				ScorersServices.deleteScorers(matchId);
			}
		}

	

		try {
			db.updateTeam(RetrieveServices.getTeam(match.getTeamA() + ""));
			db.updateTeam(RetrieveServices.getTeam(match.getTeamB() + ""));
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (RetrieveServices.getCurrentSeason().isCompleted()) {
			message.addMessage("This season is over......");
		}
		return message;
	}

	public static Message confirmAllResults(int seasonId) {
		DBAccess db = new DBAccess();
		QueryObject queryMatches = new QueryObject("matches");
		queryMatches.addWhereAndField("Played", "" + 1);
		queryMatches.addWhereAndField("SeasonID", "" + seasonId);
		UpdateObject updateMatches = new UpdateObject();
		updateMatches.addField("AddedA", 1);
		updateMatches.addField("AddedB", 1);
		Message message = new Message();
		try {
			db.update(queryMatches, updateMatches);
			// LeagueCache.refreshMatch(seasonId);

			message.addMessage("All Results have been confirmed");
		} catch (Exception e) {
			message.addMessage("Not all results have been confirmed");
		}

		return message;
	}

	public static void main(String[] args) {
		String[] scorer = { "Reda" };
		String[] goals = { "2" };
		try {
			LeagueCache.refreshAll();
			addResult(2290, 2, 3, scorer, goals, 27, null, 1);
		} catch (Exception e) {

		}
	}

}
